#include "register1.h"
#include "ui_register1.h"
#include <QMessageBox>
#include <QDebug>
#include "login.h"
#include "ui_login.h"

register1::register1(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::register1)
{
    ui->setupUi(this);
    socket = new QTcpSocket(this);

    connect(socket, &QTcpSocket::connected, this, &register1::onConnected);
    connect(socket, &QTcpSocket::readyRead, this, &register1::onReadyRead);
    connect(socket, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error), this, &register1::onError);

    socket->connectToHost("192.168.159.131", 1234);

    QLineEdit *lineEdit = ui->mima2;
    if (lineEdit) {
        lineEdit->setEchoMode(QLineEdit::Password);
    }
}

register1::~register1()
{
    delete ui;
}

void register1::on_zhuce_clicked()
{
    QString username = ui->yonghuming2->text();
    QString password = ui->mima2->text();
    QString problem = ui->wenti2->text();
    QString answer = ui->daan2->text();

    if (username.isEmpty() || password.isEmpty() || problem.isEmpty() || answer.isEmpty()) {
        QMessageBox::warning(this, "提示", "用户名，密码，验证问题，答案不能为空");
    } else {
        // 向服务器发送注册信息
        QString message = "REGISTER\n";
        message += username + "\n" + password + "\n" + problem + "\n" + answer + "\n";
        socket->write(message.toUtf8());

        qDebug() << "发送信息";
    }

}

void register1::on_fanhui_clicked()
{
    login *newWidget = new login();  // 创建新窗口对象
    newWidget->show();  // 显示新窗口
    this->close();  // 关闭当前窗口
}

void register1::onConnected() {
    qDebug() << "已连接到服务器！";
}

void register1::onReadyRead() {
    QByteArray data = socket->readAll();
    QDataStream stream(&data, QIODevice::ReadOnly);

    QString responseType;
    stream >> responseType;
    qDebug() << "接收信息";

    if (responseType == "REGISTER_SUCCESS") {
        login *newWidget = new login();  // 创建新窗口对象
        newWidget->show();  // 显示新窗口
        this->close();  // 关闭当前窗口
        QMessageBox::information(this, "提示", "注册成功");
    } else if (responseType == "REGISTER_FAIL") {
        QMessageBox::warning(this, "提示", "该用户名已被注册");
    }
}

void register1::onError(QAbstractSocket::SocketError socketError) {
    qDebug() << "Socket错误:" << socketError;
}
